SpringMVC框架(3) —— 注解

项目结构

  • java
    • controller
      • SessionController.java(Java文件)
  • resources
    • springmvc.xml(springmvc配置文件)
  • webapp
    • WEB-INF
      • pages
        • success.jsp(web页面)
        • session.jsp(web页面)
      • web.xml(web配置文件)
    • index.jsp(web页面)
    • annotation.jsp(web页面)
  • pom.xml(maven项目配置文件)

maven项目配置文件

  • 配置maven项目需要的依赖
    • spring-context
    • spring-web
    • spring-webmvc
    • servlet-api
    • jsp-api

web配置文件

  • 前端控制器(DispatcherServlet)
    • 配置一个前端控制器(<servlet>)
      • 创建前端控制器时,加载Spring配置文件(<init-param>)
      • 启动服务器时,创建前端控制器(<\load-on-startup>)
    • 配置前端控制器的作用范围(<servlet-mapping>)
  • 过滤器(CharacterEncodingFilter)
    • 配置一个过滤器(<filter>)
      • 配置编码(<init-param>):解决中文乱码
    • 配置前端控制器的作用范围(<filter-mapping>)

springmvc配置文件

  • 导入名称空间(<beans xmlns=””>)
  • 开启注解扫描(<context:component-scan base-package=””>)
  • 配置视图解析器(InternalResourceViewResolver)
    • 配置前缀(prefix -> “/WEB-INF/pages”)
    • 配置后缀(suffix -> “.jsp”)
  • 开启SpringMVC注解支持(<mvc:annotation-driven>)

Java文件

  • 表现层

      • 添加进IoC核心容器(@Controller)
      • 设置请求映射(@RequestMapping())
        • 一级目录(path=””)
        • 设置允许访问的请求方法(method=””)
        • 设置必需的参数和参数值(params=””)
          • 设置必需的请求头(headers=””)
      • 设置Session域的键值对(@SessionAttributes())
    • 方法

      • 设置请求映射(@RequestMapping())
        • 二级目录(path=””)
      • 返回值(return “success”;)
      • 参数列表(数据类型 请求参数名,数据类型 请求参数名)
        • Model:用于存储键值对至Request域
        • ModelMap:用于获取Request域中的键值对
        • SessionStatus:用于清空Session域中的键值对
      • 设置初始化方法(@ModelAttribute)
    • 方法参数

      • 获取请求参数(@RequestParam())

        • 二级目录:”/testRequestParam”
        • 请求地址:”anno/testRequestParam?name=cat”
      • 获取请求参数(@PathVariable())

        • 二级目录:”/testPathVariable/{name}”
        • 请求地址:”anno/testPathVariable/cat”
      • 获取请求体(@RequestBody)

      • 获取请求头(@RequestHeader)

      • 获取缓存(@CookieValue())

      • 获取底层Map集合的键值对(@ModelAttribute())

      • 设置Session域的键值对(@SessionAttributes())

JSP文件

  • 超链接(href=”一级目录/二级目录?请求参数=值&请求参数=值”)
  • 表单(<form action=”一级目录/二级目录” method=”post”>)

执行代码

  • 需求:在annotation.jsp页面,点击的超链接,跳转到success.jsp页面,并且在控制台输出请求消息

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>cn.water</groupId>
<artifactId>section01_Introduction</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>section01_Introduction Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<!-- 版本锁定 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>

<!-- 依赖注入 -->
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
<finalName>section01_Introduction</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>

<!-- 【Filter】 -->
<filter>
<!-- 创建过滤器 -->
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 配置编码 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- 映射 -->
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 【Servlet】 -->
<servlet>
<!-- 创建前端控制器 -->
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 创建前端控制器时,加载spring配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 启动服务器时,创建前端控制器 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 映射 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

springmvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<!-- 开启注解扫描 -->
<context:component-scan base-package="cn.water"/>

<!-- 视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/pages/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>


<!-- 开启springMVC框架注解支持 -->
<mvc:annotation-driven />


</beans>

AnnotationController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package cn.water.controller;

import cn.water.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.util.Map;

/**
* @author Water
* @date 2019/9/10 - 10:48
*/
@Controller
@RequestMapping("/anno")
/* 将键值对存储到session域 */
@SessionAttributes("message")
public class AnnotationController {

/* 【获取请求参数】 */
@RequestMapping("/testRequestParam")
public String testRequestParam(@RequestParam(name = "name") String username ){
System.out.println("请求参数:"+username);
return "success";
}

/* 【获取请求参数】 */
@RequestMapping("/testPathVariable/{name}")
public String testPathVariable(@PathVariable(name = "name") String username ){
System.out.println("请求参数:"+username);
return "success";
}

/* 【获取请求体(GET请求方式没有请求体)】 */
@RequestMapping("/testRequestBody")
public String testRequestBody(@RequestBody String body ){
System.out.println("请求体:"+body);
return "success";
}

/* 【获取请求头】 */
@RequestMapping("/testRequestHeader")
public String testRequestHeader(@RequestHeader(value = "Accept") String header ){
System.out.println("请求头:"+header);
return "success";
}

/* 【Cookie】 */
@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookieValue ){
System.out.println("Cookie:"+cookieValue);
return "success";
}

/* 【ModelAttribute】 */
/* 用于将表单提交的数据封装至JavaBean对象时,当时当数据不全时,使用ModelAttribute注释的方法将数据补全 */
// [方法一]
// @RequestMapping("/testModelAttribute")
// public String testModelAttribute(User user){
// System.out.println("testModelAttribute执行了...");
// System.out.println(user);
// return "success";
// }
// @ModelAttribute /* 先执行 */
// public User ModelAttributeMethod(String name){
// System.out.println("ModelAttributeMethod执行了...");
// User user = new User();
// user.setName(name);
// user.setAge("11");
// return user;
// }
// [方法二]
@RequestMapping("/testModelAttribute")
public String testModelAttribute(@ModelAttribute("user_name") User user){
System.out.println("testModelAttribute执行了...");
System.out.println(user);
return "success";
}
/* 将User对象存储进底层的Map集合中 */
@ModelAttribute /* 先执行 */
public void ModelAttributeMethod(String username, Map<String,User> map){
System.out.println("ModelAttributeMethod执行了...");
User user = new User();
user.setName(username);
user.setAge("11");
map.put("user_name",user);
}



@RequestMapping("testSessionAttributes")
public String testSessionAttributes(Model model){
/* 将键值对存储到request域 */
model.addAttribute("message","Hello,Request Field!");
return "session";
}

@RequestMapping("getSessionAttributes")
public String getSessionAttributes(ModelMap modelMap){
/* 获取Session域中的值 */
Object message = modelMap.get("message");
System.out.println(message);
return "session";
}

@RequestMapping("removeSessionAttributes")
public String removeSessionAttributes(SessionStatus sessionStatus){
/* 清空Session域中的值 */
sessionStatus.setComplete();
return "session";
}


}

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2><a href="controller/sayHello?username=cat">入门</a></h2>
<hr>
<h2><a href="parameters.jsp">参数绑定</a></h2>
<hr>
<h2><a href="annotation.jsp">注解</a></h2>
<hr>
</body>
</html>

annotation.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<%--
Created by IntelliJ IDEA.
User: Water
Date: 2019/9/19
Time: 14:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%-- 请求参数 --%>
<h3><a href="anno/testRequestParam?name=cat&name=dog&name=rat">获取 请求参数(RequestParam)</a></h3>
<hr>

<%-- 请求参数 --%>
<%--<a href="anno/testRequestParam?name=cat">请点击</a>--%>
<a href="anno/testPathVariable/cat">获取 请求参数(PathVariable)</a> // "cat" <br>
<a href="anno/testPathVariable/cat&dog">获取 请求参数(PathVariable)</a> // "cat&dog"
<hr>

<%-- 请求体 --%>
<form action="anno/testRequestBody" method="post">
姓名:<input type="text" name="username" /><br/>
密码:<input type="text" name="password" /><br/>
金额:<input type="text" name="money" /><br/>
<input type="submit" value="获取 请求体(RequestBody)">
</form>
<hr>

<%-- 请求头 --%>
<h3><a href="anno/testRequestHeader">获取 请求头(RequestHeader)</a></h3>
<hr>

<%-- 缓存 --%>
<h3><a href="anno/testCookieValue">获取 缓存(CookieValue)</a></h3>
<hr>

<%-- ModelAttribute --%>
<form action="anno/testModelAttribute" method="post">
姓名:<input type="text" name="username" /><br/>
<input type="submit" value="ModelAttribute">
</form>
<hr>

<a href="anno/testSessionAttributes">设置,并在浏览器查看Request域和Session域中的message值</a><br>
<a href="anno/getSessionAttributes">在控制台查看Session域中的message值</a><br>
<a href="anno/removeSessionAttributes">删除,并在浏览器查看Session域中的message值</a><br>


</body>
</html>

success.jsp

1
2
3
4
5
6
7
8
9
10
11
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>

<h3>访问成功!!!</h3>

</body>
</html>

session.jsp

1
2
3
4
5
6
7
8
9
10
11

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Request域:</h1>${requestScope.message}<br>
<h1>Session域:</h1>${sessionScope}
</body>
</html>

@RequestParam 请求参数

  • 发出请求

    1
    <a href="anno/testRequestParam?name=cat&name=dog&name=rat">获取 请求参数(RequestParam)</a>
  • 接收请求

    1
    2
    3
    4
    5
    @RequestMapping("/testRequestParam")
    public String testRequestParam(@RequestParam(name = "name") String username ){
    System.out.println("请求参数:"+username);
    return "success";
    }
  • 运行结果

    1
    请求参数:cat,dog,rat

@PathVariable 请求参数

  • 发出请求

    1
    2
    <a href="anno/testPathVariable/cat">获取 请求参数(PathVariable)</a> <br>
    <a href="anno/testPathVariable/cat&dog">获取 请求参数(PathVariable)</a>
  • 接收请求

    1
    2
    3
    4
    5
    @RequestMapping("/testPathVariable/{name}")
    public String testPathVariable(@PathVariable(name = "name") String username ){
    System.out.println("请求参数:"+username);
    return "success";
    }
  • 运行结果

    1
    2
    请求参数:cat
    请求参数:cat&dog

@RequestBody 请求体

  • 发出请求

    1
    2
    3
    4
    5
    6
    <form action="anno/testRequestBody" method="post">
    姓名:<input type="text" name="username" /><br/>
    密码:<input type="text" name="password" /><br/>
    金额:<input type="text" name="money" /><br/>
    <input type="submit" value="获取 请求体(RequestBody)">
    </form>
  • 接收请求

    1
    2
    3
    4
    5
    6
    /* 【GET请求方式没有请求体】 */
    @RequestMapping("/testRequestBody")
    public String testRequestBody(@RequestBody String body ){
    System.out.println("请求体:"+body);
    return "success";
    }
  • 运行结果

    1
    请求体:username=cat&password=111&money=999

@RequestHeader 请求头

  • 发出请求

    1
    <a href="anno/testRequestHeader">获取 请求头(RequestHeader)</a>
  • 接收请求

    1
    2
    3
    4
    5
    @RequestMapping("/testRequestHeader")
    public String testRequestHeader(@RequestHeader(value = "Accept") String header ){
    System.out.println("请求头:"+header);
    return "success";
    }
  • 运行结果

    1
    请求头:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3

@CookieValue 缓存

  • 发出请求

    1
    <a href="anno/testCookieValue">获取 缓存(CookieValue)</a>
  • 接收请求

    1
    2
    3
    4
    5
    @RequestMapping("/testCookieValue")
    public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookieValue ){
    System.out.println("Cookie:"+cookieValue);
    return "success";
    }
  • 运行结果

    1
    Cookie:93E4FB2388E1A6249DA4552C947FE2C2

@ModelAttribute

  • 发出请求

    1
    2
    3
    4
    <form action="anno/testModelAttribute" method="post">
    姓名:<input type="text" name="username" /><br/>
    <input type="submit" value="ModelAttribute">
    </form>
  • 接收请求

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    @RequestMapping("/testModelAttribute")
    public String testModelAttribute(User user){
    System.out.println("testModelAttribute执行了...");
    System.out.println(user);
    return "success";
    }

    /* 直接返回User对象 */
    @ModelAttribute /* 先执行 */
    public User ModelAttributeMethod(String name){
    System.out.println("ModelAttributeMethod执行了...");
    User user = new User();
    user.setName(name);
    user.setAge("11");
    return user;
    }
  • 运行结果

    1
    2
    3
    ModelAttributeMethod执行了...
    testModelAttribute执行了...
    User{name='cat', age='11'}

方法二

  • 接收请求
    1
    2
    3
    4
    5
    6
    7
    8
    9
    /* 将User对象存储进底层的Map集合中 */
    @ModelAttribute
    public void ModelAttributeMethod(String username, Map<String,User> map){
    System.out.println("ModelAttributeMethod执行了...");
    User user = new User();
    user.setName(username);
    user.setAge("11");
    map.put("user_name",user);
    }

设置域

  • 发出请求

    1
    <a href="anno/testSessionAttributes">设置,并在浏览器查看Request域和Session域中的message值</a>
  • 接收请求

    1
    2
    3
    4
    5
    6
    @RequestMapping("testSessionAttributes")
    public String testSessionAttributes(Model model){
    /* 将键值对存储到request域 */
    model.addAttribute("message","Hello,Request Field!");
    return "session";
    }
  • 响应页面

1
2
Request域:${requestScope.message}<br>
Session域:${sessionScope}
  • 响应结果
    1
    2
    Request域:Hello,Request Field!
    Session域:{message=Hello,Request Field!}

查看域

  • 发出请求

    1
    <a href="anno/getSessionAttributes">在控制台查看Session域中的message值</a>
  • 接收请求

    1
    2
    3
    4
    5
    6
    7
    @RequestMapping("getSessionAttributes")
    public String getSessionAttributes(ModelMap modelMap){
    /* 获取Session域中的值 */
    Object message = modelMap.get("message");
    System.out.println(message);
    return "session";
    }
  • 响应页面

1
2
Request域:${requestScope.message}<br>
Session域:${sessionScope}
  • 响应结果

    1
    2
    Request域:Hello,Request Field!
    Session域:{message=Hello,Request Field!}
  • 运行结果

1
Hello,Request Field!

删除域

  • 发出请求

    1
    <a href="anno/removeSessionAttributes">删除,并在浏览器查看Session域中的message值</a>
  • 接收请求

    1
    2
    3
    4
    5
    6
    @RequestMapping("removeSessionAttributes")
    public String removeSessionAttributes(SessionStatus sessionStatus){
    /* 清空Session域中的值 */
    sessionStatus.setComplete();
    return "session";
    }
  • 响应页面

1
2
Request域:${requestScope.message}<br>
Session域:${sessionScope}
  • 响应结果
    1
    2
    Request域:
    Session域:{}
-------------本文结束-------------
Donate comment here